<template>
  <div class="worktab">
    <!-- <vue-Scroll :ops="ops" ref="scroll"> -->
    <ul class="tabs" ref="tabs">
      <li
        v-for="(item, index) in worktabs"
        :key="item.path"
        :ref="item.path"
        :class="{ 'activ-tab': item.path === activeTab }"
        @click="clickWorktab(item.path)"
      >
        {{ item.name }}
        <el-icon
          @click.stop="closeWorktab('current', item.path)"
          v-if="index !== 0"
        >
          <close />
        </el-icon>
      </li>
    </ul>
    <!-- </vue-Scroll> -->

    <div class="right">
      <el-dropdown @command="closeWorktab">
        <div class="btn">
          <el-icon>
            <arrow-left />
          </el-icon>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item icon="el-icon-arrow-left" command="left">
              <span style="menu-txt">关闭左侧</span>
            </el-dropdown-item>
            <el-dropdown-item icon="el-icon-arrow-right" command="right">
              <span style="menu-txt">关闭右侧</span>
            </el-dropdown-item>
            <el-dropdown-item icon="el-icon-close" command="other">
              <span style="menu-txt">关闭其它</span>
            </el-dropdown-item>
            <el-dropdown-item icon="el-icon-error" command="all">
              <span style="menu-txt">关闭全部</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script lang="ts">
import { reactive, toRefs, computed, watch } from "vue";
import { useAppStore } from "@/storePinia/index";
import { RouteRecordRaw, useRouter, useRoute } from "vue-router";
export default {
  name: "WorkTab",
  setup() {
    const router = useRouter();
    const route = useRoute();
    const state: any = reactive({
      activeTab: "", // 选中的Tab 即所在的页面
      ops: {
        rail: {
          opacity: "0",
          background: undefined,
          size: "0px",
        },
        bar: {
          background: "#999",
          keepShow: false,
          size: "0px",
          minSize: 0,
        },
        scrollButton: {
          enable: true,
          background: "#cecece",
        },
        scrollPanel: {
          easing: "easeOutQuad",
          speed: 800,
        },
        vuescroll: {
          wheelScrollDuration: 600,
          wheelDirectionReverse: true,
        },
      },
      allowPath: [], // 存储当前用户可访问的路由 之后做权限管理需要用到
      worktab: computed(() => useAppStore().worktab),
      worktabs: computed(() => useAppStore().worktab.opened),
      menuList: computed(() => useAppStore().menuList),
      setting: computed(() => useAppStore().setting),
    });
    watch(route, () => {
      if (route.path !== "/login") {
        useAppStore().addWorkTab({
          name: route.meta.title,
          path: route.path,
        });
        state.activeTab = route.path;
      }
    });
    // 获取当前用户可访问的路由 之后权限需要用到
    const getCurrentUserAllowRouters = () => {
      state.allowPath = state.menuList;
      let { routes } = router.options;
      routerMatch(state.menuList, routes).then((res) => {
        state.allowPath = res;
      });
    };
    const routerMatch = (permission: Array<RouteRecordRaw>, allowRouters) => {
      return new Promise((resolve) => {
        const paths = [];
        function createRouter(permission) {
          permission.forEach((item) => {
            let { path } = item;
            let pathArr = path && path.split("/");

            if (pathArr) {
              path = pathArr[pathArr.length - 1];
            }

            if (item.children && item.children.length) {
              createRouter(item.children);
            }

            allowRouters.find((s) => {
              if (s.children) {
                s.children.find((y) => {
                  if (y.path === path) {
                    paths.push(s.path + "/" + y.path);
                  }
                });
              }
            });
          });
        }
        createRouter(permission);
        resolve(paths);
      });
    };

    // 点击选项卡 这里也只是临时的 之后权限管理等需要改
    const clickWorktab = (path: string) => {
      router.push(path);
      console.log(router);
    };

    // 关闭选项卡
    // type {current: 当前, left: 左侧, right: 右侧, other: 其它, all: 所有}
    const closeWorktab = (type: string, tabPath: string) => {
      let path = route.path;
      console.log(path, router)
      console.log(type)
      switch (type) {
        case "current":
          if (tabPath) {
            path = tabPath;
          }
          useAppStore().worktabRemove({ path, router });
          break;
        case "left":
          useAppStore().worktabRemoveLeft({ path, router });
          break;
        case "right":
          useAppStore().worktabRemoveRight({ path, router });
          break;
        case "other":
          useAppStore().worktabRemoveOther({ path, router });
          break;
        case "all":
          useAppStore().worktabRemoveAll();
          break;
      }
      console.log("object");
    };

    // 重载后选项卡默认选中项
    const initActiveWorktab = () => {
      setTimeout(() => {
        state.activeTab = route.path;
      }, 400);
    };

    // 标签导航自动定位 滚动逻辑： 标签超出可视区域自动定位
    const worktabAutoPosition = (offsetLeft, labelWidth) => {
      // let x = scrollLeft
      // let labelRight = 6
      // const scroll = this.$refs['scroll']
      // const panel = scroll.scrollPanelElm
      // const panelWidth = panel.clientWidth
      // const scrollLeft = panel.scrollLeft
      // offsetLeft += labelWidth + labelRight
      // if(offsetLeft > (panelWidth + scrollLeft)) {
      //     x = offsetLeft - panelWidth
      // }
      // if((offsetLeft - labelWidth - labelRight) < scrollLeft) {
      //     x = offsetLeft - labelWidth - labelRight
      // }
      // scroll.scrollTo({x})
    };
    initActiveWorktab();
    return {
      ...toRefs(state),
      getCurrentUserAllowRouters,
      routerMatch,
      clickWorktab,
      closeWorktab,
      initActiveWorktab,
      worktabAutoPosition,
    };
  },
  //     watch: {
  //         'worktab.current' (tab) {
  //             this.activeTab = tab.path
  //             let el = this.$refs[tab.path]
  //             let elWidth = 0
  //             let offsetLeft = 0
  //             if(el && el.length > 0) {
  //                 elWidth = el[0].clientWidth
  //                 offsetLeft = el[0].offsetLeft
  //             }
  //             this.worktabAutoPosition(offsetLeft, elWidth)
  //         },
  //         worktabs() {
  //             sessionStorage.setItem('worktab',JSON.stringify(this.worktab))
  //             // console.log(sessionStorage.getItem('worktab'))
  //         }
  // },
};
</script>

<style lang="scss" scoped>
.worktab {
  width: 100%;
  display: flex;
  justify-content: space-between;
  user-select: none;
  -moz-user-select: none;
  -webkit-user-select: none;
  padding: 8px 15px;
  box-sizing: border-box;
  background: $default-background;

  .tabs {
    width: 100px;
    display: flex;
    white-space: nowrap;
    background: transparent !important;

    li {
      height: 30px;
      line-height: 30px;
      text-align: center;
      color: #808695;
      font-size: 13px;
      padding: 0 12px;
      cursor: pointer;
      border-top: 2px solid transparent;
      transition: color 0.1s;
      background: #fff;
      border-radius: 3px;
      margin-right: 6px;

      &:hover {
        color: #515a6e;
        transition: color 0.2s;
      }

      i {
        color: #808695;
        padding: 2px;
        margin-left: 5px;
        border-radius: 50%;
        transition: all 0.2s;

        &:hover {
          background: #eee;
        }
      }
    }

    .activ-tab {
      color: $theme-color !important;
    }
  }

  .right {
    .btn {
      font-size: 16px;
      width: 32px;
      height: 32px;
      line-height: 32px;
      text-align: center;
      cursor: pointer;
      position: relative;
      top: 0;
      border-left: 1px solid #f2f2f2;
      background: #fff;
      border-radius: 3px;
      box-shadow: 0 0 5px #eee;

      &:hover ul {
        display: inline;
      }
    }
  }
}
</style>
